package com.emmmya.ocs.config;

import cn.hutool.core.util.ArrayUtil;
import com.emmmya.ocs.common.utils.ShiroUtil;
import com.emmmya.ocs.filter.HostFilter;
import com.emmmya.ocs.filter.XssFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class FilterConfig {

	@Autowired
    HostFilter hostFilter;//http host头攻击漏洞处理过滤器

	@Autowired
	ShiroUtil shiroUtil;
 
	@Bean
	public FilterRegistrationBean hostfilter() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(hostFilter);
		registration.addUrlPatterns("/*");
		registration.setName("hostFilter");
		registration.setOrder(1); // 值越小，Filter越靠前。
		return registration;
	}

	/**
	 * 防xss攻击
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<?> xssFilterRegistration() {
		FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
		// 将过滤器配置到FilterRegistrationBean对象中
		registration.setFilter(new XssFilter());
		// 给过滤器取名
		registration.setName("xssFilter");
		// 设置过滤器优先级，该值越小越优先被执行
		registration.setOrder(0);
		List<String> urlPatterns = new ArrayList<>();
		urlPatterns.add("/*");
		//这里需要填写排除上传文件的接口
		Map<String, String> paramMap = new HashMap<>();
		String join = ArrayUtil.join(shiroUtil.getAnon().toArray(), ",");
		paramMap.put("noFilterUrl", join);
		// 设置initParams参数
		registration.setInitParameters(paramMap);
		// 设置urlPatterns参数
		registration.setUrlPatterns(urlPatterns);
		return registration;
	}

}